/*
 * @Description: 存为模板
 */
/* workflowModule*/
import sendCommon from '@/handles/common/send';
import globalMethods from '@/plugins/methods';
import emitter from "@/utils/emitter";
import globalData from "@/plugins/data";
import errHandle from "@/handles/common/err-handle";

/**
 * 产生UUID，返回类型是String
 */
var UUID_seqence = 0;
function getUUID() {
    var UUIDConstants_Time = new Date().getTime() + '' + UUID_seqence++;
    if (UUID_seqence >= 100000) {
        UUID_seqence = 0;
    }

    return UUIDConstants_Time;
}

/**
 * @description: 调用存为模板接口
 * @param {function} resolve 处理完有结果之后执行
 */
async function doSaveTemplate(params) {
    let { fnx, resolve, dialog } = params;
    var moduleId = getUUID();

    // 更新数据
    fnx.contentAPI.updateMainBodyData('id', '-1');
    fnx.contentAPI.updateMainBodyData('moduleId', moduleId + '');
    // 存为个人模板, 正文的moduleTemplateId要存成-1
    fnx.contentAPI.updateMainBodyData('moduleTemplateId', '-1');

    const {  useBaseInfo } = sendCommon;
    let cap4 = useBaseInfo.baseInfo.zwIframe.isCap4;
    if (!cap4){
        //用于快速选人生成流程图信息
        await emitter.publish("sendFreeCol");
        //保存正文
        let promise = await new Promise((resolveCallBack) => {
            // const {id} = useBaseInfo.baseInfo.businessData.summary;
            // eslint-disable-next-line no-undef
            if (fnx.document) {
                fnx.document.getElementById("moduleId").value=moduleId
                fnx.document.getElementById("id").value=''
            }
            fnx.contentAPI.submit({
                checkNull: false,
                mainbodyDomains: [],
                needCheckRepeatData: false,
                needCheckRule: false,
                needSn: false,
                needSubmit: true,
                optType: 'saveAsTemplate',
                summaryId: moduleId,
                failed: () => resolveCallBack(false),
                success: () => resolveCallBack(true),
            })
        });
        if (promise === false) {
            return;
        }
    }
    //触发自由流程流程图
    await emitter.publish("sendFreeCol");
    sendCommon
        .saveAsTemplate({
            ...params,
            moduleId,
        })
        .then(
            (res) => {
                switch (res.code) {
                    case 413:
                        errHandle(
                          res.data,
                          (...arg) => {
                              console.log('action, data ', arg);
                              const [result] = arg || [];
                              if (!result) return;
                              //工作流事件弱校验
                              if (result.workflowEvent){
                                  sendCommon.saveAsTemplate({
                                      ...params,
                                      moduleId,
                                  });
                                  return;
                              }
                              if (!result.isCwp) return;
                              //表单弱校验
                              this.useBaseInfo.needCheckRule = false;
                              sendCommon.saveAsTemplate({
                                  ...params,
                                  moduleId,
                              });
                          },
                          (err) => {
                              console.log('send error', err);
                          }
                        );
                        break;

                    default:
                        globalMethods.message.success(
                            $.i18n('collaboration.newColl.susscessSaveTemplate')
                        );
                        break;
                }
            },
            (e) => {
                globalMethods.message.error($.i18n('collaboration.error.save.template.js'));
            }
        )
        .finally(() => {
            resolve();
            dialog.close(); // 关闭弹窗
        });
}

/**
 * @description: 存为模板
 * @param {function} resolve 处理完有结果之后执行
 */
async function saveAsTemplate(resolve) {
    const {  useBaseInfo } = sendCommon;

    let { templateBodyType, currentTemplateId, templateTitle } =
        useBaseInfo.baseInfo.collaborationSubmitData.colMainData;
    let template = useBaseInfo.businessData.template;
    let subject = useBaseInfo.formInfo.subject.value;
    let defaultValue = useBaseInfo.defaultSubject; // 默认标题
    
    //获取正文iframe对象
    const fnx = sendCommon.useTemplate.zwIframe.contentWindow;


    // 校验是否输入了标题, 如果校验没通过则返回
    if (!useBaseInfo.validateSubject() || !useBaseInfo.validateAttachmentUploading()) {
        resolve();
        return false;
    }

    // 缺少标题值
    var defaultSubject = $.i18n('common.default.subject.value2');
    defaultSubject == defaultValue && (defaultValue = '');
    //是否有流程
    let hasWorkflow = true;
    if (!useBaseInfo.validateProcess(false)){
        hasWorkflow = false;
    }

    // 获取正文类型：类型值有哪些？
    var ctype = fnx.contentAPI.getMainBodyData('contentType');

    // useforsavetemsubject、saveastemtype参数需要获取
    var useforsavetemsubject = template?.showSubject||subject;
    var saveastemtype = template?.type;
    useforsavetemsubject && (subject = useforsavetemsubject);

    var _temType = 'hasnotTemplate';
    saveastemtype && (_temType = saveastemtype);

    var lock = false; // 重复点击标识
    const dialog = globalMethods.dialog({
        title: $.i18n('common.toolbar.saveAs.label.rep'), //调用模板
        width: 400,
        height: 300,
        bodyStyle:'padding:0',
        maskClosable: false,
        url: `${_ctxPath}/collaboration/collaboration.do?method=saveAsTemplate&hasWorkflow=${escapeStringToHTML(
            hasWorkflow
        )}&subject=${escapeStringToHTML(
            encodeURIComponent(subject)
        )}&tembodyType=${escapeStringToHTML(templateBodyType)}&curTemId=${escapeStringToHTML(
            encodeURIComponent(currentTemplateId)
        )}&formtitle=${escapeStringToHTML(
            encodeURIComponent(templateTitle)
        )}&defaultValue=${escapeStringToHTML(defaultValue)}&ctype=${escapeStringToHTML(
            ctype
        )}&temType=${escapeStringToHTML(_temType)}`,
        onCancel() {
            dialog.close();
            resolve();
        },
        onConfirm() {
            //防止重复点击
            if (lock) {
                globalMethods.warning({
                    title: $.i18n('system.reminder.title'),
                    content: $.i18n('collaboration.common.repeat.click.js'),
                }); //请不要重复点击！
                return;
            }
            lock = true;

            // 返回值
            const result = dialog.getValue();
            if (!result) {
                return;
            }

            var over = result[0];
            var overId = result[1];
            var type = result[2];
            var subject = result[3];
            var bodyId = result[4];
            if (over == 5) {
                // 模板标题已存在，是否覆盖模板
                globalMethods.confirm({
                    title: $.i18n('common.system.hint.label'),
                    zIndex: 9999,
                    maskClosable: false,
                    content: (h) => (
                        <div>{$.i18n('collaboration.saveAsTemplate.isHaveTemplate', subject)}</div>
                    ),
                    onOk() {
                        doSaveTemplate({
                            fnx,
                            type,
                            subject,
                            overId,
                            curTemId: currentTemplateId,
                            over: 1,
                            bodyId,
                            dialog,
                            resolve,
                        });
                    },
                    onCancel() {
                        lock = false;
                    },
                });
            } else if (over == 4) {
                // 否覆盖原模板？确定则替换原个人模板的全部内容，包括名称和内容；否则新建一个模板
                globalMethods.confirm({
                    title: $.i18n('common.system.hint.label'),
                    zIndex: 9999,
                    maskClosable: false,
                    okText: $.i18n('common.button.ok.label'), // 确定
                    cancelText: $.i18n('collaboration.saveAsTemplate.create'), // 创建新模板
                    content: (h) => (
                        <div>{$.i18n('collaboration.saveAsTemplate.isHaveTemplates')}</div>
                    ),
                    onOk() {
                        doSaveTemplate({
                            fnx,
                            type,
                            subject,
                            overId,
                            curTemId: currentTemplateId,
                            over: 1,
                            bodyId,
                            dialog,
                            resolve,
                        });
                    },
                    onCancel() {
                        // 创建新模板
                        lock = false;
                        // 第1个参数，0：正常进行，直接报错，1: 存在同名，直接覆盖
                        doSaveTemplate({
                            fnx,
                            type,
                            subject,
                            overId: null,
                            curTemId: currentTemplateId,
                            over: 0,
                            bodyId,
                            dialog,
                            resolve,
                        });
                    },
                });
            } else {
                doSaveTemplate({
                    fnx,
                    type,
                    subject,
                    overId,
                    curTemId: currentTemplateId,
                    over,
                    bodyId,
                    dialog,
                    resolve,
                });
            }
        },
    });
}

export default () =>
    new Promise((resolve, reject) => {
        saveAsTemplate(resolve, reject);
    });
